package com.microservice.salmon.oauth.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
public class ClientProcessorHolder {

	private static ThreadLocal<ClientInfo> clientInfoThreadLocal = new ThreadLocal<>();

	public static void addClientInfo(ClientInfo clientInfo) {
		log.info("add client info ["+ clientInfo.getClientId() +"] to the threadLocal" );
		clientInfoThreadLocal.set(clientInfo);
	}

	public static ClientInfo getClientInfo() {
		return clientInfoThreadLocal.get();
	}

	public static void removeClientInfo() {
		log.info("delete clientId from threadLocal");
		clientInfoThreadLocal.remove();
	}

	public static String[] extractAndDecodeHeader(String header) {
		byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
		byte[] decoded;
		try {
			decoded = Base64.getDecoder().decode(base64Token);
		}
		catch (IllegalArgumentException e) {
			throw new BadCredentialsException(
					"Failed to decode basic authentication token");
		}

		String token = new String(decoded, StandardCharsets.UTF_8);

		int delim = token.indexOf(":");

		if (delim == -1) {
			throw new BadCredentialsException("Invalid basic authentication token");
		}
		return new String[] { token.substring(0, delim), token.substring(delim + 1) };
	}
}
